import cv2
import os
import numpy as np


def drawPoint(img, x, y, color=(255, 0, 0)):
    cv2.circle(img, (x, y), radius=1, color=color)


def fetchProfile(img):
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    dilated = cv2.dilate(img, kernel)
    result = dilated
    return result


def drawRegion(event, x, y, flags, param):
    _blackboard, pointList = param
    if flags == cv2.EVENT_FLAG_LBUTTON and event == cv2.EVENT_MOUSEMOVE:
        print("Mouse on ({},{}).".format(x, y))
        pointList.append((x, y))
        drawPoint(_blackboard, x, y)
        cv2.imshow('wb', _blackboard)
    if event == cv2.EVENT_RBUTTONDOWN:
        for _ in range(5):
            if len(pointList) != 0:
                x, y = pointList[-1]
                drawPoint(_blackboard, x, y, color=(0, 0, 0))
                pointList.pop()
            else:
                break
        for point in pointList:
            drawPoint(_blackboard, point[0], point[1])
        cv2.imshow('wb', _blackboard)
    if flags == cv2.EVENT_FLAG_CTRLKEY:
        result = fetchProfile(_blackboard)
        cv2.imshow('result', result)


if __name__ == '__main__':
    imageDirPath = 'display/image'
    labelDirPath = 'display/label'
    imagePathList = []
    for imageInfo in os.walk(imageDirPath):
        imagePathList = imageInfo[2]
    cv2.namedWindow('image')
    for imagePath in imagePathList:
        image = cv2.imread(imageDirPath + '/' + imagePath)
        print(imageDirPath + '/' + imagePath)
        cv2.imshow('image', image)
        blackboard = np.zeros(image.shape)
        cv2.imshow('wb', blackboard)
        drawnPointList = []
        cv2.setMouseCallback('image', drawRegion, param=[blackboard, drawnPointList])
        key = cv2.waitKey(0)
        if key & 0xFF == 27:
            break
    cv2.destroyAllWindows()
